package worktime.yft.demo.Service;

import net.minidev.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import worktime.yft.demo.Bean.RecordsProjectBean;
import worktime.yft.demo.Bean.RecordsUserBean;
import worktime.yft.demo.Entity.Record;
import worktime.yft.demo.Mapper.ProjectMapper;
import worktime.yft.demo.Mapper.RecordMapper;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

@Service
public class RecordService {
    @Autowired
    private RecordMapper recordMapper;
    @Autowired
    private ProjectMapper projectMapper;

    public void delete(int ProjectId,String UserId,String Time){
        recordMapper.delete(ProjectId,UserId,Time);
    }

    public void insert(int ProjectId,String UserId,String Time,float Effort,int Weeks){
        Record record = recordMapper.findRecordByTime(ProjectId,UserId,Time);
        if(record == null){
            recordMapper.insert(new Record(ProjectId,UserId,Time,Effort,Weeks));
        }else{
            record.setEffort(Effort);
            recordMapper.update(record);
        }
    }

    public JSONObject findRecordByUser(String UserId,String startTime,String endTime){
        JSONObject object = new JSONObject();
        int index;
        try {
            List<Integer> projects = projectMapper.findAllProjectId();
            float[][] efforts = new float[projects.size()][7];
            SimpleDateFormat simdate = new SimpleDateFormat("yyyy-MM-dd");
            int day = 24*1000*3600;
            for (Record record : recordMapper.findRecordByUser(UserId, startTime, endTime)) {
                int days = (int)(simdate.parse(record.getTime()).getTime()-simdate.parse(startTime).getTime())/day;
                index = projects.indexOf(record.getProjectId());
                if(index != -1)
                    efforts[projects.indexOf(record.getProjectId())][days] =record.getEffort();
            }
            object.put("efforts",efforts);
            return object;
        }catch (Exception e){
            System.out.println(e.getMessage());
            return null;
        }
    }

    public JSONObject findRecordByProject(String startTime, String endTime, int ProjectId,String Department){
        JSONObject object = new JSONObject();
        List<RecordsProjectBean> recordsProjectBeans;
//        List<Integer> list;
        if(Department.equals("全部")) {
            recordsProjectBeans = recordMapper.findRecordByProject(startTime, endTime, ProjectId);
//            list = recordMapper.findRecordByProjectNum(startTime,endTime,ProjectId);
        }else{
            recordsProjectBeans = recordMapper.findRecordByProjectDep(startTime,endTime,ProjectId,Department);
//            list = recordMapper.findRecordByProjectDepNum(startTime,endTime,ProjectId,Department);
        }
        String[] start = startTime.split("-");
        String[] end = endTime.split("-");
        int width = (Integer.parseInt(end[0])-Integer.parseInt(start[0]))*12 + (Integer.parseInt(end[1])-Integer.parseInt(start[1]))+1;
        int month = Integer.parseInt(start[1]);
        int year = Integer.parseInt(start[0]);
//        float[][] results = new float[list.size()][width];
        ArrayList<String> UserNames = new ArrayList<String>();
        ArrayList<float[]> results = new ArrayList<float[]>();
        for(RecordsProjectBean recordsProjectBean : recordsProjectBeans){
            if(!UserNames.contains(recordsProjectBean.getUsername())){
                UserNames.add(recordsProjectBean.getUsername());
                results.add(new float[width]);
            }
            results.get(UserNames.indexOf(recordsProjectBean.getUsername()))[(Integer.parseInt(recordsProjectBean.getTime().substring(0,4))-year)*12 + Integer.parseInt(recordsProjectBean.getTime().substring(5,7))-month] += recordsProjectBean.getEffort();
        }
        object.put("names",UserNames);
        object.put("efforts",results);
        return object;
    }

    public JSONObject findRecordByProjectWeeks(String startTime, String endTime, int ProjectId,String Department) throws ParseException {
        JSONObject object = new JSONObject();
        List<RecordsProjectBean> recordWeeksBeans;
//        List<Integer> list;
        if(Department.equals("全部")){
            recordWeeksBeans = recordMapper.findRecordByProject(startTime,endTime,ProjectId);
//            list = recordMapper.findRecordByProjectNum(startTime,endTime,ProjectId);
        }else {
            recordWeeksBeans = recordMapper.findRecordByProjectDep(startTime,endTime,ProjectId,Department);
//            list = recordMapper.findRecordByProjectDepNum(startTime,endTime,ProjectId,Department);
        }
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Calendar calendara = Calendar.getInstance();
        Calendar calendarb = Calendar.getInstance();
        Date start = format.parse(startTime);
        Date end = format.parse(endTime);
        calendara.setTime(start);
//        calendara.setFirstDayOfWeek(Calendar.MONDAY);
//        calendarb.setFirstDayOfWeek(Calendar.MONDAY);
        int weekday = calendara.get(Calendar.DAY_OF_WEEK);
        if(weekday == 1)
            weekday = 7;
        else
            weekday--;
        calendara.setTime(start);
        calendarb.setTime(end);
//        int startWeeks = calendara.get(Calendar.WEEK_OF_YEAR);
//        int endWeeks = calendarb.get(Calendar.WEEK_OF_YEAR);
        int width = (int)Math.ceil(((calendarb.getTimeInMillis() - calendara.getTimeInMillis())/(1000*60*60*24) + weekday)/7.0);

//        float[][] results = new float[list.size()][width];
        ArrayList<float[]> results = new ArrayList<float[]>();
        ArrayList<String> UserNames = new ArrayList<String>();
        for(RecordsProjectBean recordsProjectBean : recordWeeksBeans){
            if(!UserNames.contains(recordsProjectBean.getUsername())){
                UserNames.add(recordsProjectBean.getUsername());
                results.add(new float[width]);
            }
            calendarb.setTime(format.parse(recordsProjectBean.getTime()));
            results.get(UserNames.indexOf(recordsProjectBean.getUsername()))[(int)Math.ceil(((calendarb.getTimeInMillis() - calendara.getTimeInMillis())/(1000*60*60*24) + weekday)/7.0) -1] += recordsProjectBean.getEffort();
        }
        object.put("names",UserNames);
        object.put("efforts",results);
        return object;
    }

    public JSONObject findRecordByUserMon(String UserId,String startTime,String endTime){
        JSONObject object = new JSONObject();
        List<RecordsUserBean> recordsUserBeans;
//        List<Integer> list;
        if(UserId.equals("全部")) {
            recordsUserBeans = recordMapper.findRecordByUsersMon(startTime, endTime);
//            list = recordMapper.findRecordByUsersMonNum(startTime,endTime);
        }
        else {
            recordsUserBeans = recordMapper.findRecordByUserMon(startTime, endTime, UserId);
//            list = recordMapper.findRecordByUserMonNum(startTime,endTime,UserId);
        }
        String[] start = startTime.split("-");
        String[] end = endTime.split("-");
        int width = (Integer.parseInt(end[0])-Integer.parseInt(start[0]))*12 + (Integer.parseInt(end[1])-Integer.parseInt(start[1]))+1;
        int month = Integer.parseInt(start[1]);
        int year = Integer.parseInt(start[0]);
        ArrayList<float[]> results = new ArrayList<float[]>();
        ArrayList<String> ProjectNames = new ArrayList<String>();
        for(RecordsUserBean recordsUserBean : recordsUserBeans){
            if(!ProjectNames.contains(recordsUserBean.getProjectName())){
                ProjectNames.add(recordsUserBean.getProjectName());
                results.add(new float[width]);
            }
            results.get(ProjectNames.indexOf(recordsUserBean.getProjectName()))[(Integer.parseInt(recordsUserBean.getTime().substring(0,4))-year)*12 + Integer.parseInt(recordsUserBean.getTime().substring(5,7))-month] += recordsUserBean.getEffort();
        }
        object.put("ProjectNames",ProjectNames);
        object.put("efforts",results);
        return object;
    }

    public JSONObject findRecordByUserWeeks(String UserId,String startTime,String endTime) throws ParseException {
        JSONObject object = new JSONObject();
        List<RecordsUserBean> recordsUserBeans;
//        List<Integer> list;
        if(UserId.equals("全部")) {
            recordsUserBeans = recordMapper.findRecordByUsersMon(startTime, endTime);
//            list = recordMapper.findRecordByUsersMonNum(startTime,endTime);
        }
        else {
            recordsUserBeans = recordMapper.findRecordByUserMon(startTime, endTime, UserId);
//            list = recordMapper.findRecordByUserMonNum(startTime,endTime,UserId);
        }
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Calendar calendara = Calendar.getInstance();
        Calendar calendarb = Calendar.getInstance();
        Date start = format.parse(startTime);
        Date end = format.parse(endTime);
        calendara.setTime(start);
        calendara.setFirstDayOfWeek(Calendar.MONDAY);
        calendarb.setFirstDayOfWeek(Calendar.MONDAY);
        int weekday = calendara.get(Calendar.DAY_OF_WEEK);
        if(weekday == 1)
            weekday = 7;
        else
            weekday--;
        calendara.setTime(start);
        calendarb.setTime(end);
//        int startWeeks = calendara.get(Calendar.WEEK_OF_YEAR);
//        int endWeeks = calendarb.get(Calendar.WEEK_OF_YEAR);
        int width = (int)Math.ceil(((calendarb.getTimeInMillis() - calendara.getTimeInMillis())/(1000*60*60*24) + weekday)/7.0);
//        float[][] results = new float[list.size()][width];
        ArrayList<String> ProjectNames = new ArrayList<String>();
        ArrayList<float[]> results = new ArrayList<float[]>();
        for(RecordsUserBean recordsUserBean : recordsUserBeans){
            if(!ProjectNames.contains(recordsUserBean.getProjectName())){
                ProjectNames.add(recordsUserBean.getProjectName());
                results.add(new float[width]);
            }
            calendarb.setTime(format.parse(recordsUserBean.getTime()));
            results.get(ProjectNames.indexOf(recordsUserBean.getProjectName()))[(int)Math.ceil(((calendarb.getTimeInMillis() - calendara.getTimeInMillis())/(1000*60*60*24) + weekday)/7.0) -1] += recordsUserBean.getEffort();
        }
        object.put("ProjectNames",ProjectNames);
        object.put("efforts",results);
        return object;
    }
}
